package demo.shiro.action;

import demo.shiro.service.UserService;
import java.util.Map;
import org.smart4j.framework.ioc.annotation.Inject;
import org.smart4j.framework.mvc.DataContext;
import org.smart4j.framework.mvc.annotation.Action;
import org.smart4j.framework.mvc.annotation.Request;
import org.smart4j.framework.mvc.bean.Params;
import org.smart4j.framework.mvc.bean.View;
import org.smart4j.security.exception.RegisterException;

@Action
public class RegisterAction {

    @Inject
    private UserService userService;

    @Request.Get("/register")
    public View index() {
        // 转发到注册页面
        return new View("register.jsp");
    }

    @Request.Post("/register")
    public View submit(Params params) {
        // 获取表单数据
        String username = params.getString("username");
        String password = params.getString("password");

        // 调用注册服务
        try {
            Map<String, Object> fieldMap = params.getFieldMap();
            userService.register(fieldMap);
        } catch (RegisterException e) {
            DataContext.Request.put("exception", e.getName());
            return index();
        }

        // 调用登录服务并重定向到空间页面
        userService.login(username, password, false);
        return new View("/space");
    }
}
